<?php
namespace app\models;

use app\event\ModelOptimisticEvent;
use think\Db;
use think\Model;

class Permission extends Model
{

    protected $pk = 'id';
    protected $table = 'permission';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    protected $json = ['auth'];

    // 模型初始化
    protected static function init()
    {
        /**
         * 高并发请求时更新时，使用乐观锁，用版本号来防止幻更
         */
        self::observe(ModelOptimisticEvent::class);
    }

    public function searchNameAttr($query, $value, $data)
    {
        if (! empty($value)) {
            $query->where('name', 'like', "%$value%");
        }
    }

    public function searchStatusAttr($query, $value, $data)
    {
        if (! empty($value)) {
            $query->where('status', $value);
        }
    }

    public function getStatusAttr($value, $data)
    {
        $status = [1 => '启用', 2 => '禁用'];
        return $status[$data['status']];
    }

    public function roles()
    {
        return $this->belongsToMany('Role', RolePermissionRelation::class, 'role_id', 'permission_id');
    }

    public function permissionGroup()
    {
        return $this->belongsTo(PermissionGroup::class, 'group_id');
    }
}
